# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# Odoo Connector
# QQ:35350428
# 邮件:sale@100china.cn
# 手机：13584935775
# 作者：'amos'
# 公司网址： www.odoo.pw  www.100china.cn
# Copyright 昆山一百计算机有限公司 2012-2016 Amos
# 日期：2014-06-18
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

import json
from lxml import etree
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools.misc import ustr

class ir_ui_view_inherit(models.Model):
    _inherit = "ir.ui.view"

    button_line_ids = fields.One2many("button.line", "view_id",string=u'视图按钮',)
    field_line_ids = fields.One2many("field.line", "field_id",string=u'视图字段',)

    @api.multi
    def button_analysis(self):
        buttons = self.env['button.line'].search([('view_id', '=', self.id)])
        buttons.unlink()
        doc = etree.XML(self.arch_base)
        view = etree.SubElement(doc, 'form')
        for child in view.xpath('//button'):
            if child.get('groups'):
                groups_arr = child.get('groups').split(',')
                group_id = []
                if len(groups_arr) > 1:
                    for g in groups_arr:
                        domain = [('model', '=', 'res.groups'), ('module', '=', g.split('.')[0]),
                                  ('name', '=', g.split('.')[1])]
                        group_id.append(self.env['ir.model.data'].search(domain).res_id)
                else:
                    domain = [('model', '=', 'res.groups'), ('module', '=', groups_arr[0].split('.')[0]),
                              ('name', '=', groups_arr[0].split('.')[1])]
                    group_id.append(self.env['ir.model.data'].search(domain).res_id)
                self.env['button.line'].create(
                    {"button_string": child.get('string'), "button_name": child.get('name'), "view_id": self.id,
                     "group_ids": [(6, 0, group_id)],'sequence':child.sourceline})
            else:
                self.env['button.line'].create(
                    {"button_string": child.get('string'), "button_name": child.get('name'), "view_id": self.id,'sequence':child.sourceline})

    @api.multi
    def button_save_access(self):
        view = etree.fromstring(self.arch)
        val = {}
        for b in self.button_line_ids:
            str = ''
            for g in b.group_ids:
                domain = [('model', '=', 'res.groups'), ('res_id', '=', g.id)]
                eid = self.env['ir.model.data'].search(domain)
                if eid:
                    str = str + eid.complete_name + ','
            xpath_str = "//button[@name='" + b.button_name + "']"
            for child in view.xpath(xpath_str):
                if b.sequence == child.sourceline:
                    if str == '':
                        if 'groups' in child.attrib:
                            del child.attrib['groups']
                    else:
                        child.set("groups", str[:-1])

        res = etree.tostring(view, encoding="utf-8").replace('\t', '')
        self.write({"arch": res})



    @api.multi
    def field_analysis(self):
        buttons = self.env['field.line'].search([('field_id', '=', self.id)])
        buttons.unlink()
        doc = etree.XML(self.arch_base)
        for child in doc.xpath('//field'):
            if child.get('groups'):
                groups_arr = child.get('groups').split(',')
                group_id = []
                if len(groups_arr) > 1:
                    for g in groups_arr:
                        domain = [('model', '=', 'res.groups'), ('module', '=', g.split('.')[0]),
                                  ('name', '=', g.split('.')[1])]
                        group_id.append(self.env['ir.model.data'].search(domain).res_id)
                else:
                    domain = [('model', '=', 'res.groups'), ('module', '=', groups_arr[0].split('.')[0]),
                              ('name', '=', groups_arr[0].split('.')[1])]
                    group_id.append(self.env['ir.model.data'].search(domain).res_id)
                self.env['field.line'].create(
                    {"field_string": child.get('string'), "field_name": child.get('name'), "field_id": self.id,
                     "group_ids": [(6, 0, group_id)],'sequence':child.sourceline})
            else:
                self.env['field.line'].create(
                    {"field_string": child.get('string'), "field_name": child.get('name'), "field_id": self.id,'sequence':child.sourceline})

    @api.multi
    def field_save_access(self):
        view = etree.XML(self.arch_base)
        val = {}
        for b in self.field_line_ids:
            str = ''
            for g in b.group_ids:
                domain = [('model', '=', 'res.groups'), ('res_id', '=', g.id)]
                eid = self.env['ir.model.data'].search(domain)
                if eid:
                    str = str + eid.complete_name + ','

            xpath_str = "//field"
            for child in view.xpath(xpath_str):
                print b.field_name
                print b.sequence
                print child.sourceline
                if b.sequence == child.sourceline:
                    if str == '':
                        if 'groups' in child.attrib:
                            del child.attrib['groups']
                    else:
                        child.set("groups", str[:-1])

        res = etree.tostring(view, encoding="utf-8").replace('\t', '')
        self.write({"arch": res})



class field_line(models.Model):
    _name = "field.line"
    _order = 'sequence asc'

    field_name = fields.Char(u"字段")
    field_string = fields.Char(u"字段名称")
    group_ids = fields.Many2many("res.groups",string=u'权限组',)
    field_id = fields.Many2one("ir.ui.view",string=u'视图',)
    sequence = fields.Integer(string=u'排序', default=0)

class button_line(models.Model):
    _name = "button.line"
    _order = 'sequence asc'

    button_name = fields.Char(u"按钮事件名称")
    button_string = fields.Char(u"按钮名称")
    group_ids = fields.Many2many("res.groups",string=u'权限组',)
    view_id = fields.Many2one("ir.ui.view",string=u'视图',)
    sequence = fields.Integer(string=u'排序', default=0)


class res_groups_inherit(models.Model):
    _inherit = "res.groups"

    @api.multi
    def button_create_complete_name(self):
        domain = [('model', '=', 'res.groups'), ('res_id', '=', self.id)]
        res = self.env['ir.model.data'].search(domain)
        if not res:
            self.env['ir.model.data'].create(
                {"module": self.category_id.name, "model": "res.groups", "name": self.name, "res_id": self.id})
